<template>
	<view class="tui-container">
		<view v-if="useType==='default'" class="tui-upload-box">
			<view class="tui-image-item" v-for="(item,index) in imageList" :key="index">
				<image :src="item" class="tui-item-img" @tap.stop="previewImage(index)"></image>
				<view v-if="!forbidDel" class="tui-img-del" @tap.stop="delImage(index)"></view>
				<view v-if="statusArr[index]!=1" class="tui-upload-mask">
					<view class="tui-upload-loading" v-if="statusArr[index]==2"></view>
					<text class="tui-tips">{{statusArr[index]==2?'上传中...':'上传失败'}}</text>
					<view class="tui-mask-btn" v-if="statusArr[index]==3" @tap.stop="reUpLoad(index)" hover-class="tui-hover"
					 :hover-stay-time="150">重新上传</view>
				</view>
			</view>
			<view v-if="isShowAdd" class="tui-upload-add" @tap="chooseImage">
				<view class="tui-upload-icon iconfont iconaddApp"></view>
			</view>
		</view>
		<view v-if="useType==='video'" class="tui-upload-box">
			<view class="tui-image-item video-item" v-for="(item,index) in imageList" :key="index">
				<image @tap.stop="previewImg(item)" v-if="['jpg','jpeg','png','gif','JPG','JPEG','PNG','GIF'].includes(item.split('.')[item.split('.').length-1])" :src="item" class="tui-item-img"></image>
				<template v-else>
					<!-- #ifndef APP-PLUS -->
					<video :src="item" :autoplay='false' :show-fullscreen-btn="true" show-center-play-btn controls class="tui-item-img" ></video>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS -->
					<view class="video-black" @tap="videoshow(item)">
						<image  src="~@/static/img/videoPlay.png" mode="aspectFill" class="video-icon"></image>
						<image class="black-img" :src="item+'?x-oss-process=video/snapshot,t_0,f_jpg'" mode="aspectFill"></image>
					</view>
					<!-- #endif -->
				</template>
				<view v-if="!forbidDel" class="tui-img-del" @tap.stop="delImage(index)"></view>
				<view v-if="statusArr[index]!=1" class="tui-upload-mask">
					<view class="tui-upload-loading" v-if="statusArr[index]==2"></view>
					<text class="tui-tips">{{statusArr[index]==2?'上传中...':'上传失败'}}</text>
					<view class="tui-mask-btn" v-if="statusArr[index]==3" @tap.stop="reUpLoad(index)" hover-class="tui-hover"
					 :hover-stay-time="150">重新上传</view>
				</view>
			</view>
			<view v-if="isShowAdd" class="tui-upload-add" @tap="chooseVideoImage">
				<view class="tui-upload-icon iconfont iconaddApp"></view>
			</view>
		</view>
		
		<view v-else-if="useType==='idCard'" class="tui-upload-box">
			<view class="idCard-image-item" v-for="(item,index) in imageList" :key="index">
				<image :src="item" class="upload-img" @tap.stop="previewImage(index)" mode="aspectFit"></image>
				<view v-if="!forbidDel" class="tui-img-del" @tap.stop="delImage(index)"></view>
				<view v-if="statusArr[index]!=1" class="tui-upload-mask">
					<view class="tui-upload-loading" v-if="statusArr[index]==2"></view>
					<text class="tui-tips">{{statusArr[index]==2?'上传中...':'上传失败'}}</text>
					<view class="tui-mask-btn" v-if="statusArr[index]==3" @tap.stop="reUpLoad(index)" hover-class="tui-hover"
					 :hover-stay-time="150">重新上传</view>
				</view>
			</view>
			<view class="idCard-upload" @tap="chooseImage">
				<view class="idCard-upload-inner">
					<view class="iconfont iconcamera"></view>
				</view>
				
			</view>
		</view>
		
		<view v-if="useType==='qrCode'" class="tui-upload-box">
			<!-- <view class="tui-image-item" v-for="(item,index) in imageList" :key="index">
				<image :src="item" class="tui-item-img" @tap.stop="previewImage(index)"></image>
				<view v-if="!forbidDel" class="tui-img-del" @tap.stop="delImage(index)"></view>
				<view v-if="statusArr[index]!=1" class="tui-upload-mask">
					<view class="tui-upload-loading" v-if="statusArr[index]==2"></view>
					<text class="tui-tips">{{statusArr[index]==2?'上传中...':'上传失败'}}</text>
					<view class="tui-mask-btn" v-if="statusArr[index]==3" @tap.stop="reUpLoad(index)" hover-class="tui-hover"
					 :hover-stay-time="150">重新上传</view>
				</view>
			</view> -->
			<view @tap="chooseImage('qrCode')">
				<slot></slot>
			</view>
		</view>
		<!--app端视频播放-->
		<template v-if="videoPlay">
			<view class="mask-video" @tap="videoPlay = !videoPlay"></view>
			<video class="screen-video" :show-fullscreen-btn="false" :autoplay="true" controls id="myvideo" 
			:src="videoUrl"></video>
		</template>
	</view>
</template>

<script>
	export default {
		name: 'tuiUpload',
		props: {
			// 清空flag
			clearFlag: {
				type: Boolean,
				default: false
			},
			useType: {//被使用的情况
				type: String,
				default: "default"
			},
			
			//初始化图片路径
			value: {
				type: Array,
				default () {
					return []
				}
			},
			//禁用删除
			forbidDel: {
				type: Boolean,
				default: false
			},
			//禁用添加
			forbidAdd: {
				type: Boolean,
				default: false
			},
			//服务器地址
			serverUrl: {
				type: String,
				default: "so-fast-fs/fs/common/aliyunfile/upload",
			},
			//服务器地址
			uploadPath: {
				type: String,
				default: ""
			},
			//限制数
			limit: {
				type: Number,
				default: 9
			},
			//项目名，默认为 file
			fileKeyName: {
				type: String,
				default: "file"
			},
			//上传额外参数
			bucketType: {
				type: String,
				default: "dr"
			}
		},
		data() {
			return {
				//图片地址
				imageList: [],
				//上传状态：1-上传成功 2-上传中 3-上传失败
				statusArr: [],
				videoPlay: false,
				videoPlay: false,
				videoUrl: '', //全屏播放视频的URL
			}
		},
		created() {
			this.imageList = [...this.value];
			for (let item of this.imageList) {
				this.statusArr.push("1")
			}
		},
		watch:{
			clearFlag(val) {
				if(val) {
					this.imageList = [];
				}
			}
		},
		computed: {
			isShowAdd() {
				let isShow = true;
				if (this.forbidAdd || (this.limit && this.imageList.length >= this.limit)) {
					isShow = false;
				}
				return isShow
			}
		},
		methods: {
			//app端评价页视频播放
			videoshow(item) {
				//e 是通过点击事件拿到的视屏地址
				this.videoUrl = item;
				this.videoContext = uni.createVideoContext("myvideo", this);
				this.videoContext.requestFullScreen({
					direction: 0 //控制全屏的时候视屏旋转多少度 
				});
				this.videoContext.play();
				this.videoPlay = true; // 显示播放盒子
			},
			chooseVideoImage(){
				uni.showActionSheet({
					title:"选择上传类型",
					itemList: ['图片','视频'],
					success: (res) => {
						console.log(res)
						if(res.tapIndex == 0){
							this.chooseImage()
						} else {
							this.chooseVideo()
						}
					}
				})
			},
			// 重新上传
			reUpLoad(index) {
				this.$set(this.statusArr, index, "2")
				this.change()
				this.uploadImage(index, this.imageList[index]).then(() => {
					this.change()
				}).catch(() => {
					this.change()
				})
			},
			change() {
				let status = ~this.statusArr.indexOf("2") ? 2 : 1
				if (status != 2 && ~this.statusArr.indexOf("3")) {
					// 上传失败
					status = 3
				}
				this.$emit('complete', {
					status: status,
					imgArr: this.imageList
				})
			},
			chooseImage: function(type) {
				let _this = this;
				if(type==='qrCode'){
					this.delImage(0);//替换时删除刚才的
				}
				uni.chooseImage({
					count: _this.limit - _this.imageList.length,
					success: function(e) {
						let imageArr = [];
						for (let i = 0; i < e.tempFilePaths.length; i++) {
							let len = _this.imageList.length;
							if (len >= _this.limit) {
								uni.showToast({
									title: `最多可上传${_this.limit}张图片`,
									icon: "none"
								});
								break;
							}
							let path = e.tempFilePaths[i]
							imageArr.push(path)
							_this.imageList.push(path)
							_this.statusArr.push("2")
						}
						_this.change()

						let start = _this.imageList.length - imageArr.length
						for (let j = 0; j < imageArr.length; j++) {
							let index = start + j
							//服务器地址
							if (_this.serverUrl) {
								_this.uploadImage(index, imageArr[j]).then(() => {
									_this.change()
								}).catch(() => {
									_this.change()
								})
							} else {
								//无服务器地址则直接返回成功
								_this.$set(_this.statusArr, index, "1")
								_this.change()
							}
						}
					}
				})
			},
			chooseVideo: function(type) {
				let _this = this;
				if(type==='qrCode'){
					this.delImage(0);//替换时删除刚才的
				}
				uni.chooseVideo({
					count: _this.limit - _this.imageList.length,
					success: function(e) {
						let imageArr = [];
						console.log(e)
						if(e.size / 1024 / 1024 > 10){
							uni.showToast({
								title: '请上传10M以内的视频文件',
								icon: "none"
							});
							return;
						}
						
						// for (let i = 0; i < e.tempFilePaths.length; i++) {
						// 	let len = _this.imageList.length;
						// 	if (len >= _this.limit) {
						// 		uni.showToast({
						// 			title: `最多可上传${_this.limit}张图片`,
						// 			icon: "none"
						// 		});
						// 		break;
						// 	}
						// 	let path = e.tempFilePaths[i]
						// 	imageArr.push(path)
						// 	_this.imageList.push(path)
						// 	_this.statusArr.push("2")
						// }
						let len = _this.imageList.length;
						if (len >= _this.limit) {
								uni.showToast({
									title: `最多可上传${_this.limit}张图片`,
									icon: "none"
								});
								return;
							}
							let path = e.tempFilePath
							console.log(':上传视频')
							console.log(path)
							imageArr.push(path)
							_this.imageList.push(path)
							_this.statusArr.push("2")
						_this.change()
			
						let start = _this.imageList.length - imageArr.length
						for (let j = 0; j < imageArr.length; j++) {
							let index = start + j
							//服务器地址
							if (_this.serverUrl) {
								_this.uploadImage(index, imageArr[j]).then(() => {
									_this.change()
								}).catch(() => {
									_this.change()
								})
							} else {
								//无服务器地址则直接返回成功
								_this.$set(_this.statusArr, index, "1")
								_this.change()
							}
						}
					}
				})
			},
			uploadImage: function(index, url) {
				let _this = this;
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$util.interfaceUrl() + this.serverUrl,
						filePath: url,
						name:'files',
						formData:{'bucketType':this.bucketType?this.bucketType:'dr'},
						header:{"Authorization":this.$util.getToken()},
						
						success: (res) => {
							console.log(res)
							if (res.statusCode == 200) {
								//返回结果 此处需要按接口实际返回进行修改
								let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
								//判断code，以实际接口规范判断
								if (d.status === 0) {
									// 上传成功 d.url 为上传后图片地址，以实际接口返回为准
									d.data[0] && (_this.imageList[index] = d.data[0])
									_this.$set(_this.statusArr, index, d.data[0] ? "1" : "3")
								} else {
									// 上传失败
									_this.$set(_this.statusArr, index, "3")
								}
								resolve(index)
							} else {
								_this.$set(_this.statusArr, index, "3")
								reject(index)
							}
						},
						fail: (res) => {
							_this.$set(_this.statusArr, index, "3")
							reject(index)
						}
					})
				})

			},
			removeOneImage(){//身份证识别不过时调用
				this.imageList.splice(0, 1)
				this.statusArr.splice(0, 1)
			},
			delImage: function(index) {
				this.imageList.splice(index, 1)
				this.statusArr.splice(index, 1)
				this.$emit("remove", {
					index: index
				})
				this.change()
			},
			previewImage: function(index) {
				if (!this.imageList.length) return;
				uni.previewImage({
					current: this.imageList[index],
					loop: true,
					urls: this.imageList
				})
			},
			previewImg(item) {
				let imageList=[]
				imageList.push(item)
				// if (!this.imageList.length) return;
				uni.previewImage({
					current: imageList[0],
					indicator:"none",
					// loop: true,
					urls: imageList
				})
			},
		}
	}
</script>

<style>
	
	@font-face {
		font-family: 'tuiUpload';
		src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATcAA0AAAAAByQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAAEwAAAABoAAAAciR52BUdERUYAAASgAAAAHgAAAB4AKQALT1MvMgAAAaAAAABCAAAAVjxvR/tjbWFwAAAB+AAAAEUAAAFK5ibpuGdhc3AAAASYAAAACAAAAAj//wADZ2x5ZgAAAkwAAADXAAABAAmNjcZoZWFkAAABMAAAAC8AAAA2FpiS+WhoZWEAAAFgAAAAHQAAACQH3QOFaG10eAAAAeQAAAARAAAAEgwAACBsb2NhAAACQAAAAAwAAAAMAEoAgG1heHAAAAGAAAAAHwAAACABEgA2bmFtZQAAAyQAAAFJAAACiCnmEVVwb3N0AAAEcAAAACgAAAA6OMUs4HjaY2BkYGAAYo3boY/i+W2+MnCzMIDAzb3qdQj6fwPzf+YGIJeDgQkkCgA/KAtvAHjaY2BkYGBu+N/AEMPCAALM/xkYGVABCwBZ4wNrAAAAeNpjYGRgYGBl0GJgZgABJiDmAkIGhv9gPgMADTABSQB42mNgZGFgnMDAysDA1Ml0hoGBoR9CM75mMGLkAIoysDIzYAUBaa4pDA7PGJ9xMjf8b2CIYW5gaAAKM4LkANt9C+UAAHjaY2GAABYIVmBgAAAA+gAtAAAAeNpjYGBgZoBgGQZGBhBwAfIYwXwWBg0gzQakGRmYnjE+4/z/n4EBQksxSf6GqgcCRjYGOIeRCUgwMaACRoZhDwCiLwmoAAAAAAAAAAAAAAAASgCAeNpdjkFKw0AARf/vkIR0BkPayWRKQZtYY90ohJju2kOIbtz0KD1HVm50UfEmWXoAr9ADOHFARHHzeY//Fx8Ci+FJfIgdJFa4AhgiMshbrCuIsLxhFJZVs+Vl1bT1GddtbXTC3OhohN4dg4BJ3zMJAnccyfm468ZzHXddrH9ZKbHzdf9n/vkY/xv9sPQXgGEvBrHHwst5kTbXLE+YpYVPkxepPmW94W16UbdNJd6f3SAzo5W7m1jaKd+8ZZIvk5nlKw9SK6Wle7BLS3f/bTzQLmfAF2T1NsQAeNp9kD1OAzEQhZ/zByQSQiCoXVEA2vyUKRMp9Ailo0g23pBo1155nUg5AS0VB6DlGByAGyDRcgpelkmTImvt6PObmeexAZzjGwr/3yXuhBWO8ShcwREy4Sr1F+Ea+V24jhY+hRvUf4SbuFUD4RYu1BsdVO2Eu5vSbcsKZxgIV3CKJ+Eq9ZVwjfwqXMcVPoQb1L+EmxjjV7iFa2WpDOFhMEFgnEFjig3jAjEcLJIyBtahOfRmEsxMTzd6ETubOBso71dilwMeaDnngCntPbdmvkon/mDLgdSYbh4FS7YpjS4idCgbXyyc1d2oc7D9nu22tNi/a4E1x+xRDWzU/D3bM9JIbAyvkJI18jK3pBJTj2hrrPG7ZynW814IiU68y/SIx5o0dTr3bmniwOLn8owcfbS5kj33qBw+Y1kIeb/dTsQgil2GP5PYcRkAAAB42mNgYoAALjDJyIAOWMGiTIxMjMxsKak5qSWpbFmZiRmJ+QAmgAUIAAAAAf//AAIAAQAAAAwAAAAWAAAAAgABAAMABAABAAQAAAACAAAAAHjaY2BgYGQAgqtL1DlA9M296nUwGgA+8QYgAAA=) format('woff');
		font-weight: normal;
		font-style: normal;
	}
	
	.mask-video {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 9999;
	}
	
	.screen-video {
		position: fixed;
		left: 50%;
		top: 50%;
		margin-top: -50%;
		margin-left: -50%;
		width: 100%;
	}
	
	.tui-upload-icon {
		/* font-family: "tuiUpload" !important;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale; */
		padding: 10rpx;
	}

	/* .tui-icon-plus:before {
		content: "\e609";
	} */
	.tui-container{
		width: 100%;
		height: 100%;
	}
	.tui-upload-box {
		width: 100%;
		height: 100%;
		display: flex;
		flex-wrap: wrap;
		position: relative;
	}

	.tui-upload-add {
		width: 200rpx;
		height: 200rpx;
		font-size: 68rpx;
		font-weight: 100;
		color: #888;
		background-color: #F7F7F7;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
	}
	
	.video-item {
		margin-right: 18rpx !important;
		margin-bottom: 18rpx !important;
	}
	
	.video-item:last-child {
		margin-right: 0 !important;
	}
	
	.tui-image-item {
		width: 200rpx;
		height: 200rpx;
		position: relative;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		
	}

	.tui-image-item:nth-of-type(3n) {
		margin-right: 0;
	}

	.tui-item-img {
		width: 200rpx;
		height: 200rpx;
		display: block;
	}
	
	.video-black {
		width: 200rpx;
		height: 200rpx;
		/* background: #000000; */
		position: relative;
	}
	.black-img {
		width: 100%;
		height: 100%;
	}
	.video-icon {
		width: 60rpx;
		height: 60rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		margin-left: -30rpx;
		margin-top: -30rpx;
	}

	.tui-img-del {
		width: 44rpx;
		height: 44rpx;
		position: absolute;
		right: -10rpx;
		top: -10rpx;
		background: #EB0909;
		border-radius: 50%;
		color: white;
		font-size: 34rpx;
		z-index: 999;
		box-sizing: border-box;
		text-align: center;

	}

	.tui-img-del::before {
		content: '';
		width: 16rpx;
		height: 1px;
		position: absolute;
		left: 15rpx;
		top: 21rpx;
		background: #fff;
	}

	.tui-upload-mask {
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		padding: 40rpx 0;
		box-sizing: border-box;
		background: rgba(0, 0, 0, 0.6);
		border-radius: 16rpx;
	}

	.tui-upload-loading {
		width: 28rpx;
		height: 28rpx;
		border-radius: 50%;
		border: 2px solid;
		border-color: #B2B2B2 #B2B2B2 #B2B2B2 #fff;
		animation: tui-rotate 0.7s linear infinite;
	}

	@keyframes tui-rotate {
		0% {
			transform: rotate(0);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.tui-tips {
		font-size: 26rpx;
		color: #fff;
	}

	.tui-mask-btn {
		padding: 6rpx 16rpx;
		border-radius: 40rpx;
		text-align: center;
		font-size: 24rpx;
		color: #fff;
		border: 1rpx solid #fff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.tui-hover {
		opacity: 0.5;
	}
	
	.idCard-upload{
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top:0;
		z-index: 10;
	}
	.idCard-upload-inner{
		width: 200rpx;
		height: 200rpx;
		line-height: 200rpx;
		text-align: center;
		background: linear-gradient(151deg, #F69E97 0%, #EA655E 100%);
		color: #fff;
		border-radius: 50%;
		margin:44rpx auto;
	}
	.idCard-upload-inner .iconfont{
		font-size: 90rpx;
	}
	.idCard-image-item{
		width: 100%;
		height: 100%;
		border-radius: 16rpx;
		background: rgba(0,0,0,.9);
		box-shadow: 0 0 12rpx #eee;
		position: absolute;
		top:0;
		left: 0;
		z-index: 20;
	}
	.upload-img{
		max-width: 100%;
		height: 100%;
		margin: 0 auto;
		display: block;
		width: auto;
	}
</style>
